package es.indra.druida.desktop.utils;

import java.security.NoSuchAlgorithmException;

public class SecurityUtils {
	public static boolean comparePasswords(String testPassword, String password, String passwordHash) throws NoSuchAlgorithmException{
		if (password==null)
			password="";
		if (passwordHash==null)
			passwordHash="";
		//password=password.replaceAll("^\\s*","").replaceAll("\\s*$","");
		//testPassword=testPassword.replaceAll("^\\s*","").replaceAll("\\s*$","");
		if (passwordHash!=""){ //valido por hash
			String testPasswordHash=generateHash(testPassword);
			if (!testPasswordHash.equals(passwordHash)){
				return false;
			}
		}else if (password!=""){//valido por comparacion directa
			if (!testPassword.equals(password)){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * Generate hash from String.
	 * 
	 * @param loginPassword
	 *            the login password
	 * 
	 * @return the string
	 * 
	 * @throws NoSuchAlgorithmException
	 *             the no such algorithm exception
	 */
	public static String generateHash(String loginPassword) throws NoSuchAlgorithmException {
		SHA1Encoder encoder=new SHA1Encoder();
		return encoder.getHash(loginPassword);
	}
	
}
